<?php

    class import_export_model extends CI_Model {

        public function __construct() {
            parent::__construct();
		    $this->load->dbutil();
        }
    
        public function import($file_content) {
        	
            $this->db->query("SET FOREIGN_KEY_CHECKS = 0");

            $file_array = explode(';', $file_content);
			
            // Delete Byte-order-mark from beginning of the file
            if (count($file_array) > 0) {
                if (strlen($file_array[0]) > 0 && ord($file_array[0][0]) == 239) {
                    $file_array[0] = substr($file_array[0], 3);
                }
            }
            
            foreach($file_array as $query) {
                $ok = false;
                for ($j = 0; $j < strlen($query); $j++) {
                    if (ord($query[$j]) != 10 && ord($query[$j]) != 13 && $query[$j] != '\t' && $query[$j] != ' ') {
                        $ok = true;
                        break;
                    }
                }
                if ($ok) {
                    if (ord($query[0]) == 239) {
                        
                    }
                    $this->db->query($query);  
                }
            }
    
            $this->db->query("SET FOREIGN_KEY_CHECKS = 1");  
        }
        
        public function export_db() {

            $prefs = array(
                'tables'      => array(),           // Array of tables to backup.
                'ignore'      => array(),           // List of tables to omit from the backup
                'format'      => 'txt',             // gzip, zip, txt
                'filename'    => 'backup.sql',      // File name - NEEDED ONLY WITH ZIP FILES
                'add_drop'    => TRUE,              // Whether to add DROP TABLE statements to backup file
                'add_insert'  => TRUE,              // Whether to add INSERT data to backup file
                'newline'     => "\n"               // Newline character used in backup file
              );


            $backup =& $this->dbutil->backup($prefs); 

            $this->load->helper('file');
            write_file('backup/backup.sql', $backup);

            $this->load->helper('download');
            force_download('backup.sql', $backup); 
        }

		function load_table($table_name){			
			//return $query = $this->db->query("SELECT * FROM $table_name");
            return $query = $this->db->get($table_name);
		}
		
		function import_csv(){
			

		}
		
		

    }
    
?>